package com.misboot.document.controller;

import com.misboot.document.utils.BaseUtils;
import cn.ewsd.common.utils.StringUtils;
import com.misboot.document.model.Attachment;
import com.misboot.document.service.AttachmentService;
import com.misboot.document.utils.PageUtil.PageParam;
import com.misboot.document.utils.PageUtil.PageSet;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//本地文件上传
@Controller
@RequestMapping("/attachment")
public class AttachmentsController extends DocumentBaseController {

    @Resource
    private AttachmentService attachmentService;

    @Value("${my.upload-dir}")
    private String uploadDir;


    /**
     * @MethodName 获取分页数据集
     * @Description
     * @Param pageParam
     * @Return java.lang.Object
     * @Author 朱永敬<zhuyongjing@zuoyour.com>
     * @Date 2020/12/10 9:35 上午
     */
    @ResponseBody
    @RequestMapping(value = "/getPageSetData")
    public Object getPageSetData(PageParam pageParam) {
        String filterStr = "";
        filterStr = BaseUtils.filterSort(request);
        PageSet<Attachment> pageSet = attachmentService.getPageSet(pageParam, filterStr);
        return pageSet;
    }

    /**
     * @MethodName 根据puuid获取list数据集
     * @Description
     * @Param pageParam
 * @Param puuid
     * @Return java.lang.Object
     * @Author 朱永敬<zhuyongjing@zuoyour.com>
     * @Date 2020/12/10 9:35 上午
     */
    @ResponseBody
    @RequestMapping(value = "/getListByPuuid")
    public Object getListByPuuid(PageParam pageParam, String puuid) {
        PageSet<Attachment> pageSet = new PageSet<>();
        if (!StringUtils.isNullOrEmpty(puuid)) {
            String filterSort = BaseUtils.filterSort(request, " and puuid = '" + puuid + "'");
            pageSet = attachmentService.getPageSet(pageParam, filterSort);
        }
        return pageSet;
    }

    /** 根据uuid获取详情
     * @MethodName
     * @Description
     * @Param null
     * @Return
     * @Author 朱永敬<zhuyongjing@zuoyour.com>
     * @Date 2020/12/10 9:36 上午
     */
    @ResponseBody
    @RequestMapping(value = "/getDetailByUuid")
    public Object getDetailByUuid() {
        String uuid = request.getParameter("uuid");
        Attachment info = attachmentService.selectByPrimaryKey(uuid);
        return info;
    }


    /** 获取文件上传路径
     * @MethodName
     * @Description
     * @Param null
     * @Return
     * @Author 朱永敬<zhuyongjing@zuoyour.com>
     * @Date 2020/12/10 9:37 上午
     */
    public String getUploadDir(String filtType) {
        String uploadTypeDir = uploadDir + "/uploads/" + filtType;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy" + File.separator + "MM" + File.separator + "dd");
        Date date = new Date();
        String ymd = sdf.format(date);
        uploadTypeDir += File.separator + ymd + File.separator;
        return uploadTypeDir;
    }

    @ResponseBody
    @RequestMapping(value = "/md5Validate")
    public Object md5Validate() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("isHave", false);
        return map;
    }

    /**
     * 单个附件上传
     *
     * @param request
     * @return
     * @
     */
    @ResponseBody
    @RequestMapping(value = "/upload")
    public Object upload(HttpServletRequest request) throws Exception {

        request.setCharacterEncoding("UTF-8");

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

        //定义允许上传的文件扩展名
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,pptx,htm,html,txt,zip,rar,gz,bz2,pdf");

        Map<String, Object> returnMap = new HashMap<String, Object>();

        String fileName;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 上传文件
            MultipartFile mf = entity.getValue();
            long fileSize = mf.getSize();
            fileName = mf.getOriginalFilename();
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            // 获得文件类型，放入相应的文件夹
            String fileType = "";
            Boolean allowUpload = false;
            for (Map.Entry<String, String> vo : extMap.entrySet()) {
                if (vo.getValue().indexOf(fileExt) > -1) {
                    fileType = vo.getKey();
                    allowUpload = true;
                    break;
                }
            }

            if (!allowUpload) {
                returnMap.put("statusCode", 300);
                returnMap.put("title", "操作提示");
                returnMap.put("message", "不允许上传该类文件！");
                return returnMap;
            }

            fileType = "".equals(fileType) ? "file" : fileType;
            String uploadDir = getUploadDir(fileType);
            // 创建文件夹
            File file = new File(uploadDir);
            if (!file.exists()) {
                file.mkdirs();
            }
            // 生成保存到服务器的文件名
            String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date()) + "_" + BaseUtils.getFixLengthNum(10000, 99999) + "." + fileExt;
            File uploadFile = new File(uploadDir + "/" + newFileName);
            uploadDir = uploadDir.replace("\\", "/");
            try {
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
                save("uplodify", request.getParameter("module"), request.getParameter("category"), request.getParameter("puuid"), fileExt, fileSize, fileName, newFileName, uploadDir.substring(uploadDir.indexOf("uploads") - 1) + newFileName);
                String filepath = "/" + uploadDir.substring(uploadDir.indexOf("uploads")) + newFileName;
                returnMap.put("statusCode", 200);
                returnMap.put("title", "操作提示");
                returnMap.put("message", "上传成功");
                returnMap.put("filePath", filepath);
            } catch (IOException e) {
                e.printStackTrace();
                returnMap.put("statusCode", 300);
                returnMap.put("title", "操作提示");
                returnMap.put("message", "上传失败");
            }
        }
        return returnMap;
    }

    /**
     * 多个附件上传，同时接收多个附件，如ajaxFileUploader上传工具
     *
     * @param request
     * @return
     * @
     */
    @ResponseBody
    @RequestMapping(value = "/multiUpload")
    public Object multiUpload(HttpServletRequest request) throws Exception {
        request.setCharacterEncoding("UTF-8");

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        Map<String, String[]> params = multipartRequest.getParameterMap();

        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        List<MultipartFile> multiFileMap = multipartRequest.getMultiFileMap().get("files");

        //定义允许上传的文件扩展名
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,pptx,htm,html,txt,zip,rar,gz,bz2,pdf");

        Map<String, Object> returnMap = new HashMap<String, Object>();

        String fileName;
        //for (Map.Entry<String, List<MultipartFile>> entity : multiFileMap.entrySet()) {
        for (int i = 0; i < multiFileMap.size(); i++) {
            // 上传文件
            MultipartFile mf = multiFileMap.get(i);
            long fileSize = mf.getSize();
            fileName = mf.getOriginalFilename();
            //fileName = URLDecoder.decode(fileName, "UTF-8");

            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

            // 获得文件类型，放入相应的文件夹
            String fileType = "";
            for (Map.Entry<String, String> vo : extMap.entrySet()) {
                if (vo.getValue().indexOf(fileExt) > -1) {
                    fileType = vo.getKey();
                    break;
                }
            }
            fileType = "".equals(fileType) ? "file" : fileType;
            String uploadDir = getUploadDir(fileType);
            // 创建文件夹
            File file = new File(uploadDir);
            if (!file.exists()) {
                file.mkdirs();
            }
            // 生成保存到服务器的文件名
            String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date()) + "_" + BaseUtils.getFixLengthNum(10000, 99999) + "." + fileExt;
            File uploadFile = new File(uploadDir + "/" + newFileName);
            try {
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
                //save("uplodify", request.getParameter("module"), request.getParameter("category"), request.getParameter("puuid"), fileExt, fileSize, fileName, newFileName, uploadDir.substring(uploadDir.indexOf("uploads") - 1) + newFileName);
                returnMap.put("success", true);
            } catch (IOException e) {
                e.printStackTrace();
                returnMap.put("success", false);
            }
        }
        return returnMap;
    }


    private Map<String, Object> getError(String message) {
        Map<String, Object> msg = new HashMap<String, Object>();
        msg.put("error", 1);
        msg.put("message", message);
        return msg;
    }

    @RequestMapping("/download")
    public ResponseEntity<byte[]> download() throws Exception {
        String uuid = request.getParameter("uuid");
        Attachment attach = attachmentService.selectByPrimaryKey(uuid);
        String path = uploadDir + attach.getFilePath();
        File file = new File(path);
        HttpHeaders headers = new HttpHeaders();
        String fileName = new String(attach.getFileName().getBytes("UTF-8"), "iso-8859-1");//为了解决中文名称乱码问题
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

    /**
     * @MethodName pdfStreamHandeler
     * @Description 返回pdf流文件
     * @Param request
     * @Param response
     * @Return void
     * @Author 宋景民<songjingmin @ zuoyoutech.com>
     * @Date 2019/1/21 11:31
     */
    @RequestMapping(value = "/pdfStreamHandeler")
    public void pdfStreamHandeler(HttpServletRequest request, HttpServletResponse response) {
        String uuid = request.getParameter("uuid");
        Attachment attach = attachmentService.selectByPrimaryKey(uuid);

        //String realPath = request.getSession().getServletContext().getRealPath("/");
        //String path = realPath + attach.getFilePath();
        String path = uploadDir + attach.getFilePath();
        File file = new File(path);
        byte[] data = null;
        try {
            // 解决请求头跨域问题（IE兼容性  也可使用该方法）
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setContentType("application/pdf");
            FileInputStream input = new FileInputStream(file);
            data = new byte[input.available()];
            input.read(data);
            response.getOutputStream().write(data);
            input.close();
        } catch (Exception e) {
        }
    }

    public void save(String source, String module, String category, String puuid, String fileType, Long fileSize, String fileName, String newFileName, String filePath) {
        Attachment attachment = new Attachment();
        attachment.setSource(source);
        attachment.setModule(module);
        attachment.setCategory(category);
        attachment.setPuuid(puuid);
        attachment.setFileType(fileType);
        attachment.setFileSize(fileSize);
        attachment.setFileName(fileName);
        attachment.setFilePath(filePath);
        attachmentService.insertSelective(getSaveData(attachment));
    }

    /**
     * 批量保存附件信息
     *
     * @return
     * @
     */
    @ResponseBody
    @RequestMapping("/batchSave")
    public Integer batchSave(String puuid, String file1, String file2, String file3, String file4, String file5) {
        Attachment attachment = new Attachment();
        attachment.setPuuid(puuid);

        Integer result = 0;
        if (!StringUtils.isNullOrEmpty(file1)) {
            attachment.setFileName(file1);
            attachmentService.insertSelective(getSaveData(attachment));
            result++;
        }
        if (!StringUtils.isNullOrEmpty(file2)) {
            attachment.setFileName(file2);
            attachmentService.insertSelective(getSaveData(attachment));
            result++;
        }
        if (!StringUtils.isNullOrEmpty(file3)) {
            attachment.setFileName(file3);
            attachmentService.insertSelective(getSaveData(attachment));
            result++;
        }
        if (!StringUtils.isNullOrEmpty(file4)) {
            attachment.setFileName(file4);
            attachmentService.insertSelective(getSaveData(attachment));
            result++;
        }
        if (!StringUtils.isNullOrEmpty(file5)) {
            attachment.setFileName(file5);
            attachmentService.insertSelective(getSaveData(attachment));
            result++;
        }
        return result;
    }


    /**
     * @MethodName 文件表数据修改
     * @Description
     * @Param uuid
     * @Param fileName
     * @Param fileVersion
     * @Param fileStatus
     * @Return java.lang.Object
     * @Date 2020/12/10 9:33 上午
     */
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Object update(String uuid, String fileName, String fileVersion, String fileStatus) {
        int result = attachmentService.updateFileNameAndFileVersionAndFileStatusAndUuid(fileName, fileVersion, fileStatus, uuid);
        return result == 1  ? success("数据更新成功") : failure("数据更新失败");
    }

    /**
     * @MethodName 文件表数据删除
     * @Description
     * @Param uuid
     * @Return java.lang.Object
     * @Author 朱永敬<zhuyongjing@zuoyour.com>
     * @Date 2020/12/10 9:34 上午
     */
    @ResponseBody
    @RequestMapping("/delete")
    public Object delete(String[] uuid) throws Exception {
        Integer resule = 0;
        for (int i = 0; i < uuid.length; i++) {
            attachmentService.deleteByPrimaryKey(uuid[i]);
            resule++;
        }
        return resule > 0 ? success("删除成功") : failure("删除失败");
    }


}
